﻿using Autofac.Integration.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.ApplicationRuntime;
using Slam;
using Slam.Configuration;
using SlamCms.Common;
using SlamCms.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Slam.SharePoint;

namespace SlamCms.SharePoint.Core
{
	public class SlamCmsApplication : SPHttpApplication, IContainerProviderAccessor
	{
		static IContainerProvider _containerProvider;
		
		public IContainerProvider ContainerProvider
		{
			get { return _containerProvider; }
			internal set { _containerProvider = value; }
		}

		protected void Application_Start(object sender, EventArgs e)
		{
			Bootstrapper.Run(this);
			_initialized = false;
		}

		internal static readonly object _requestLock = new object();
		internal static bool _initialized;

		protected void Application_BeginRequest(object sender, EventArgs e)
		{
			//if initialized, do not bother to synchronize
			if (!_initialized)
				lock (_requestLock)
				{
					//only the first to lock should proceed
					if (!_initialized)
					{
						SetDefaultContentTypeTags();
						_initialized = true;
					}
				}
		}

		protected void SetDefaultContentTypeTags()
		{
			IConfigurationManager configurationManager = ComponentService.GetInstance<IConfigurationManager>();
			foreach (var dataMapping in configurationManager.DataMappings)
			{
				foreach (var type in dataMapping.Value.GetAllTypes())
				{
					string defaultTags = dataMapping.Value.GetTypeAttribute(type.Id, type.Name, "DefaultTags");
					string contentTypeName = dataMapping.Value.GetTypeAttribute(type.Id, type.Name, "ContentItemType");
					if (!contentTypeName.IsNullOrEmpty() && !defaultTags.IsNullOrEmpty())
					{
						var contentType = SlamCmsContext.Data.ContentTypes.Where(c => c.Title == contentTypeName).FirstOrDefault();
						if (contentType != null)
						{
							SlamCmsContext.SharePoint.WithElevatedPrivileges().SiteCollection(ConfigurationManager.Environment.DefaultApplication.AdminUrl).Site(Constants.SiteNames.GlobalSettings, gs =>
							{
								gs.AllowUnsafeUpdates = true;
								SPList contentTypes = gs.Lists.TryGetList(Constants.ListNames.ContentTypes);
								if (contentTypes != null)
								{
									SPFieldLookupValueCollection defaultTagLookupValues = new SPFieldLookupValueCollection();
									foreach (string defaultTag in defaultTags.Split(','))
									{
										var tag = SlamCmsContext.Data.Tags.FirstOrDefault(t => t.Identifier.Equals(defaultTag, StringComparison.OrdinalIgnoreCase));
										defaultTagLookupValues.Add(new SPFieldLookupValue(tag.ListRelativeId, tag.Identifier));
									}
									var contentTypeItem = contentTypes.GetItemBySlamId(contentType.ContentTypeId);
									contentTypeItem["Default Tags"] = defaultTagLookupValues;
									contentTypeItem.SystemUpdate(false);
								}
							});
						}
					}
				}
			}
		}
	}
}
